$(function () {
    let orders = new Orders();
    $(".view-button").on("click", function () {
        $(".window-button").empty();
        orders.getOrderByOrderId($(this).attr("order-id")).then(res => {
            let orderJson = JSON.parse(res);
            console.log(orderJson)
            $(".tracking-number").text(orderJson.ordersId)
            $(".addressee").text(orderJson.address.addressName)
            $(".mobile-phone-number").text(orderJson.address.addressPhone)
            $(".delivery-address").text(orderJson.address.addressProvince +
                " " + orderJson.address.addressCity +
                " " + orderJson.address.addressDistrict +
                " " + orderJson.address.fullAddress)
            $(".total-price").text(orderJson.paymentPrice + "元")

            if (orderJson.freight === 0) {
                $(".freight").text("免运费")
            } else {
                $(".freight").text(orderJson.freight + "元")
            }
            //是否使用优惠卷
            if (orderJson.couponCredit !== 0) {
                $(".coupon-credit").text(orderJson.couponCredit + "元")
                $(".use-coupon-name").text(orderJson.coupons.couponTitle)
                $(".use-coupon-discount").text((parseFloat(orderJson.coupons.discount) / 2 * 10) + "折")
            } else {
                $(".coupon").html("<div class='use-coupon'><a>使用优惠卷 :</a>" +
                    "<span style='margin-left: 5px'>未使用优惠卷</span></div>")
            }
            let textUtil = new Text_util();
            $(".place-order-date").text(textUtil.formatDateTime(orderJson.placeOrderDate))
            if (orderJson.ordersStatus === 4) {
                $(".estimated-time-arrival").text(textUtil.formatDateTime(orderJson.estimatedTimeArrival))
                $(".order-status").text("未发货")
                $(".window-button").append("<button class='shipments'>发货</button>")
                $(".window-button").append("<button class='cancel'>取消</button>")
            } else if (orderJson.ordersStatus === 0) {
                $(".order-status").text("未支付")
                $(".window-button").append("<button class='cancel' style='margin-left: 160px;'>取消</button>")
            }
            $(".total-number").text(orderJson.totalMerchandise)
            if (orderJson.paymentMethods === 0) {
                $(".payment-methods").text("支付宝支付")
            }

            orders.getWarehouseById(orderJson.warehouseId).then(res => {
                let recommendWarehouseJson = JSON.parse(res);
                $("#warehouse").append(`<option value="${recommendWarehouseJson.warehouseId}">
                                            ${recommendWarehouseJson.warehouseName}
                                    </option>`)
                orders.getAllWarehousesExcept(orderJson.warehouseId).then(res => {
                    let warehouseJson = JSON.parse(res);
                    for (const warehouse of warehouseJson) {
                        $("#warehouse").append(`<option value="${warehouse.warehouseId}">
                                            ${warehouse.warehouseName}
                                    </option>`)
                    }
                })
            })

            let arrNumber = orderJson.numberProducts.split(",");
            let index = 0;

            $($(".table-body")[1]).empty()
            $("#warehouse").empty()
            for (const commodity of orderJson.commodityList) {
                let gift = commodity.gifts || {commodity: {commodityName: "无", giftsNumber: 0}}
                let row = "<div class='table-row'> " +
                    "<div class='table-cell commodity-id'>" + commodity.commodityId + "</div> " +
                    "<div class='table-cell' style='width: 15%' title='" + commodity.commodityName + "'>"
                    + commodity.commodityName + "</div> " +
                    "<div class='table-cell'>" + commodity.commodityPrice + "</div> " +
                    "<div class='table-cell quantity-purchased'>" + arrNumber[index] + "</div> " +
                    "</div> " +
                    "<div class='drop-down-more'> <div style='display: flex;'> " +
                    "<div class='product-images'> " +
                    "<img src='http://localhost:8083/resource_packs/images/" +
                    commodity.commodityImages + "'" +
                    " alt='商品图片' title='" + commodity.commodityName + "'> " +
                    "</div>"
                if (commodity.gifts !== undefined) {
                    row += "<div class='product-more-detailed'> " +
                        " <div class='product-gifts'><span class='product-gifts-title'>赠品</span>" +
                        "<a class='product-gifts-name'>" + gift.commodity.commodityName + "</a>" +
                        "<span class='gifts-inventory'>库存:</span>" +
                        "<a class='gifts-inventory-number'>" + gift.giftsNumber + "</a>" +
                        " </div>"
                }
                row += "<div class='specification'>" + commodity.commodityName
                if (commodity.commoditySpecification !== undefined) {
                    for (const commoditySpecification of commodity.commoditySpecification) {
                        row += "&nbsp;<span class='specification-name'>" +
                            commoditySpecification.specificationName
                            + "</span>"
                    }
                }
                row += "<div class='insurance'>"
                if (commodity.commodityInsurances !== undefined) {
                    for (const commodityInsurance of commodity.commodityInsurances) {
                        row += "<span class='insurance-title'>" + commodityInsurance.insuranceTitle + "</span>"
                    }
                }
                row += "<div class='warehouse'><a class='product-inventory-title'>商品库存:</a><span class='product-inventory'>" +
                    commodity.commodityWarehouse.detailsInventory
                    + "</span><a class='purchase-limit-title'>商品限购:</a><span class='purchase-limit'>" +
                    commodity.commodityWarehouse.purchaseLimit +
                    "</span></div>"
                row += "</div></div>"

                row += "</div></div>"
                $($(".table-body")[1]).append(row)
                index++;
            }
            $($(".window")[0]).css("display", "block")
            $(".orders-table-body .table-row ").on("click", function () {
                $(this).next().stop().slideToggle();
            });
            $(".shipments").on("click", function () {
                // console.log($("#warehouse").val())
                for (let i = 0; i < $(".product-inventory").length; i++) {

                    let inventory = $($(".product-inventory")[i]).text();
                    let quantity = $($(".quantity-purchased")[i]).text();
                    let commodityId = $($(".commodity-id")[i]).text();
                    let shippingMethod = $("#shipping-method").val()
                    let logisticsCompanies = $(".logistics-companies").val()
                    let logisticsStation = $("#logistics-station").val();

                    console.log((parseInt(inventory) - parseInt(quantity)))
                    if (parseInt(inventory) > parseInt(quantity)) {
                        console.log(commodityId)

                        orders.ordersShipments(commodityId, (parseInt(inventory) - parseInt(quantity)),
                            shippingMethod, logisticsCompanies, logisticsStation, $(".tracking-number").text()).then(res => {
                            console.log(res)
                            if (textUtil.clearSpaces(res) === "true") {
                                location.reload();
                            }
                        })
                    } else {
                        alert("超过库存！")
                        return;
                    }
                }
            })
            $("#warehouse").on("change", function () {
                let warehouseId = $(this).val();
                let orderId = $(".tracking-number").text();
                orders.updateWarehouseIdByOrderId(orderId, warehouseId).then(res => {
                    console.log(res)
                    location.reload();
                })
            })
            $(".cancel").on("click", function () {
                $(".window").css("display", "none")
            })
            $(".pop-ups-down").on("click",function () {
                $(".window").css("display", "none")
            })
        })
    })
    $(".logistics-companies").on("change", function () {
        let selectedValue = $(this).val();
        $("#logistics-station").empty();
        getLogisticsStations(selectedValue);
    })
    getLogisticsStations($($(".selected-logistics-companies")[0]).val())

    function getLogisticsStations(logisticsCompanyId) {
        orders.getLogisticsStationsByLogisticsCompanyId(logisticsCompanyId).then(res => {
            let logisticsStationJson = JSON.parse(res);
            console.log(logisticsStationJson)
            for (const logisticsStation of logisticsStationJson) {
                let option = `<option value="${logisticsStation.logisticsCompaniesId}">
                                            ${logisticsStation.logisticsStationName}
                                    </option>`
                $("#logistics-station").append(option)
            }
        })
    }

    $(".inquire-button").on("click", function () {
        let nameOrId = $(".nameOrId").val();
        let currentPage = $(".sift-function").attr("current-page");
        let totalPages = $(".sift-function").attr("page-size");
        let dateSort = $(".chronological-ordering:checked").val()
        let state = $("#state").val();

        orders.orderManagement(dateSort, currentPage, totalPages, state,nameOrId,108).then(res => {
            // 提取返回的 HTML 页面中 <body> 标签的内容
            let bodyContent = $("<div>").html(res).find(".son-body");

            // 将内容替换到指定元素中
            $(".son-body").html(bodyContent.html());
            $.getScript("/www.xiaomi.com/other/component/jquery.min.js");
            $.getScript("/www.xiaomi.com/other/scripts/background/orders.js");
            $.getScript("/www.xiaomi.com/other/scripts/background/home.js");
        })
    })
    $(".search-img").on("click", function () {
        let nameOrId = $(".nameOrId").val();
        let currentPage = $(".sift-function").attr("current-page");
        let totalPages = $(".sift-function").attr("page-size");
        let dateSort = $(".chronological-ordering:checked").val()
        let state = $("#state").val();

        orders.orderManagement(dateSort, currentPage, totalPages, state, nameOrId,108).then(res => {
            // 提取返回的 HTML 页面中 <body> 标签的内容
            let bodyContent = $("<div>").html(res).find(".son-body");

            // 将内容替换到指定元素中
            $(".son-body").html(bodyContent.html());
            $.getScript("/www.xiaomi.com/other/component/jquery.min.js");
            $.getScript("/www.xiaomi.com/other/scripts/background/orders.js");
            $.getScript("/www.xiaomi.com/other/scripts/background/home.js");
        })
    })
    $(".logistics-company-management").on("click", function () {

        $($(".window")[1]).css("display", "block");

    })

    $('.logistics-companie-table-body .table-row').click(function () {
        $(this).next('.table-dropdown').stop().slideToggle();
        orders.getLogisticsStationsByLogisticsCompanyId($(this).next('.table-dropdown').attr("logistics-companies-id")).then(res => {
            let logisticsStationJson = JSON.parse(res);
            console.log(logisticsStationJson)
            $(".logistics-station-tbody").empty();
            for (const logisticsStation of logisticsStationJson) {
                let tr = `<tr class="logistics-station logistics-station-td"><td>${logisticsStation.logisticsStationId}</td>
<td class="data-station logistics-station-td">${logisticsStation.logisticsStationName}</td>
<td class="data-station logistics-station-td">${logisticsStation.logisticsStationProvince}</td>
<td class="data-station logistics-station-td">${logisticsStation.logisticsStationCity}</td>
<td class="data-station logistics-station-td">${logisticsStation.logisticsStationDistrict}</td>
<td class="data-station logistics-station-td">${logisticsStation.logisticsStationDeliveryman}</td>
<td class="data-station logistics-station-td">${logisticsStation.logisticsStationPhone}</td>
<td><button class="remove-station logistics-station-td" logistics-station-id="${logisticsStation.logisticsStationId}">删除</button></td></tr>`
                $(".logistics-station-tbody").append(tr)
            }
            $(".remove-station").on("click", function () {
                let stationId = $(this).attr("logistics-station-id");
                console.log(stationId)
                let removeStation = orders.removeStation(stationId);
                console.log(removeStation)
            })
        })
    });

    $('.table-dropdown').on("click", function (event) {
        event.stopPropagation();
    });

    $(document).on('click', '.update', function () {
        updateCompanies(this);
    });

    $(document).on('click', '.save', function () {
        let row = $(this).closest('.table-row');
        let dataRow = row.find('.data-row');
        let logisticsCompaniesJson = {
            logisticsCompaniesId: $($(dataRow).prev()[0]).text().trim(),
            logisticsCompaniesName: $(dataRow[0]).find('.data-row-input').val(),
            logisticsCompaniesHead: $(dataRow[1]).find('.data-row-input').val(),
            logisticsCompaniesPhone: $(dataRow[2]).find('.data-row-input').val(),
            logisticsCompaniesMailbox: $(dataRow[3]).find('.data-row-input').val()
        }

        let jsonPromise = orders.updateLogisticsCompaniesById(JSON.stringify(logisticsCompaniesJson));
        $(this).parent().html('<button class="update">修改</button>');
        for (let i = 0; i < dataRow.length; i++) {
            let rowText = $(dataRow[i]);
            $(dataRow[i]).html(rowText.find('.data-row-input').val());
        }

    });

    function updateCompanies(my) {
        let row = $($(my).parent().parent())
        let dataRow = row.find('.data-row');
        for (let i = 0; i < dataRow.length; i++) {
            let rowInput = $(dataRow[i]).text().trim();
            $(dataRow[i]).html(`<input class="data-row-input" value="${rowInput}" style="width: 100px" />`)
            $($(my).parent()).html(`<button class="save">保存</button>`)
        }
    }

    $(".save-button").on("click", function () {
        let logisticsCompaniesJson = {
            logisticsCompaniesName: $($(".save-logistaics-companies-input")[0]).val(),
            logisticsCompaniesHead: $($(".save-logistaics-companies-input")[1]).val(),
            logisticsCompaniesPhone: $($(".save-logistaics-companies-input")[2]).val(),
            logisticsCompaniesMailbox: $($(".save-logistaics-companies-input")[2]).val(),
        }
        let addLogisticsCompanies = orders.addLogisticsCompanies(logisticsCompaniesJson);
        console.log(addLogisticsCompanies)
        location.reload()
    })
    let gaud = new Gaud();
    $(".save-button-logistics-station").on("click", function () {
        gaud.getCurrentLocation().then(function (res) {
            let city = gaud.getCity().then(resCity => {
                gaud.getCurrentLatitudeAndLongitude(res).then(resLongitude => {
                    console.log(resLongitude)
                    console.log(resCity)
                    $($(".save-logistaics-statuion-input")[0]).val()
                    let logisticsStationJson = {
                        logisticsStationName:$($(".save-logistaics-statuion-input")[0]).val(),
                        logisticsStationProvince:resCity.province,
                        logisticsStationCity:resCity.city,
                        logisticsStationDistrict:resCity.district,
                        logisticsStationLongitude:resLongitude.lng,
                        logisticsStationLatitude:resLongitude.lat,
                        logisticsStationDeliveryman:$($(".save-logistaics-statuion-input")[1]).val(),
                        logisticsStationPhone:$($(".save-logistaics-statuion-input")[2]).val(),
                        logisticsCompaniesId:$("#affiliated-logistics-company").val()
                    }
                    let booleanPromise = orders.addLogisticsStation(logisticsStationJson);
                    console.log(booleanPromise)
                    location.reload();
                });
            });
        });
    })
    $(".pop-ups-down").on("click",function () {
        $(".window").css("display", "none")
    })
})

